package com.cman777.springc.monitor;

import com.cman777.springc.monitor.interceptor.MonitorInterceptor;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import io.prometheus.client.Counter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author chenzhicong
 * @time 2021/1/12 17:35
 */
@Configuration
public class MetricsConfig {
    @Autowired
    private PrometheusMeterRegistry prometheusMeterRegistry;
    @Bean
    public Counter requestTotalCountCollector(){
        Counter counter = Counter.build()
                .name("http_requests_total")
                .labelNames("path", "method")
                .help("http请求总计数").register(prometheusMeterRegistry.getPrometheusRegistry());

        return counter;

    }
    @Bean
    public WebMvcConfigurer monitorInterceptorConfig(Counter requestTotalCountCollector){
        return new WebMvcConfigurer() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new MonitorInterceptor(requestTotalCountCollector));
            }
        };
    }



}
